package com.molichuxing.service.impl;

import com.alibaba.fastjson.JSON;
import com.molichuxing.entity.JobFailure;
import com.molichuxing.entity.LineChartDto;
import com.molichuxing.framework.utils.RedisUtil;
import com.molichuxing.service.StatisticsOrderService;
import com.molichuxing.services.infrastructure.dto.request.create.StatisticsOrderCreateDto;
import com.molichuxing.services.infrastructure.dto.response.CarDto;
import com.molichuxing.services.infrastructure.dto.response.OrderExclusivelDto;
import com.molichuxing.services.infrastructure.dto.response.OrderSubscribeDto;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.StatisticsOrderTypeEnum;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.molichuxing.exception.StatisticsRedisKey.*;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 17:04 2019/11/14
 * @Modified By:
 **/
@Service("statisticsOrderService")
public class StatisticsOrderServiceImpl implements StatisticsOrderService {

    private static final Logger log = Logger.getLogger(StatisticsOrderServiceImpl.class);

    @Resource
    private OrderScheduleService orderScheduleService;

    @Resource
    private OrderExclusivelService orderExclusivelService;

    @Resource
    private OrderSubscribeService orderSubscribeService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private CarService carService;

    @Resource
    private IovCarService iovCarService;

    @Resource
    private BasicdataStatisticsOrderService basicdataStatisticsOrderService;

    /**
     * 逾期未还订单数量
     * @return
     */
    @Override
    public Boolean orderOverdueHandler() throws Exception {

        try {
            Integer count = orderScheduleService.getOrderOverdue();

            redisUtil.set(OVERDUE_ORDERS,String.valueOf(count));
        } catch (Exception e) {
            log.error("查询逾期未还订单数量异常：" , e);
            throw new Exception("查询逾期未还订单数量异常");
        }
        return true;
    }

    /**
     * 订阅/专属超时未还车数量
     * @return
     */
    @Override
    public Boolean orderOvertimeHandler() throws Exception {

        try {
            //专属超时未还车数量
            Integer exclusivelCount = orderExclusivelService.getExclusivelOvertimeCount();

            redisUtil.set(EXCLUSIVE_OVERTIME,String.valueOf(exclusivelCount));

            //订阅超时未还车数量

            Integer subscribeCount = orderSubscribeService.getSubscribeOvertimeCount();

            redisUtil.set(SUBSCRIBE_OVERTIME,String.valueOf(subscribeCount));

        } catch (Exception e) {
            log.error("订阅/专属超时未还车数量异常：" , e);
            throw new Exception("订阅/专属超时未还车数量异常");
        }
        return true;
    }

    /**
     * 订阅/专属超程订单数量
     * @return
     * @throws Exception
     */
    @Override
    public Boolean orderOverrideHandler() throws Exception {

        //订阅
        Integer subscribeCount = 0;
        //查询所有用车中的订阅订单信息
        List<OrderSubscribeDto> orderSubscribeDtoList = orderSubscribeService.getSubscribeTradeUse();

        if(orderSubscribeDtoList == null || orderSubscribeDtoList.isEmpty()){
            log.info("查询所有用车中的订阅订单信息为空");
            redisUtil.set(SUBSCRIBE_OVERRIDE,String.valueOf(subscribeCount));
        }else{
            //取车辆id
            List<Integer> subscribeCarIds = new ArrayList<>(orderSubscribeDtoList.size());
            orderSubscribeDtoList.forEach(orderSubscribeDto -> {
                if (orderSubscribeDto.getCarId() != null && orderSubscribeDto.getCarId() > 0) {
                    subscribeCarIds.add(orderSubscribeDto.getCarId());
                }
            });

            // 根据车辆ids查询车辆信息
            Map<Integer, CarDto> subscribeCarMap = carService.getCarByIds(subscribeCarIds);
            if (subscribeCarMap == null || subscribeCarMap.isEmpty()) {
                log.error("订阅根据车辆ids查询车辆信息异常：车辆信息(ids:" + subscribeCarMap + ")查询异常");
                return false;
            }

            // 车架号vins
            List<String> subscribeVins = subscribeCarMap.entrySet().stream().map(e -> e.getValue().getVin()).collect(Collectors.toList());
            // 根据车架号查询车辆行驶里程信息
            Map<String, Integer> subscribeCurrentMileageMap = iovCarService.getCurrentMileage(subscribeVins);
            if (subscribeCurrentMileageMap == null || subscribeCurrentMileageMap.isEmpty()) {
                log.error("订阅根据车辆ids查询车辆里程信息异常：车辆信息(ids:" + subscribeVins + ")查询异常");
                return false;
            }

            for (OrderSubscribeDto orderSubscribeDto:orderSubscribeDtoList) {
                //当前车辆的行驶里程
                if(null != subscribeCurrentMileageMap.get(subscribeCarMap.get(orderSubscribeDto.getCarId()).getVin())){
                    // 当前车辆的行驶里程 > 当前车辆的预警里程
                    if(subscribeCurrentMileageMap.get(subscribeCarMap.get(orderSubscribeDto.getCarId()).getVin()) > orderSubscribeDto.getWarningMileage() ){
                        subscribeCount++;
                    }
                }
            }

            redisUtil.set(SUBSCRIBE_OVERRIDE,String.valueOf(subscribeCount));
        }



        //专属
        Integer exclusivelCount = 0;
        //查询所有用车中的专属订单信息
        List<OrderExclusivelDto> orderExclusivelDtoList = orderExclusivelService.getExclusivelTradeUse();
        if(orderExclusivelDtoList == null || orderExclusivelDtoList.isEmpty()){
            log.info("查询所有用车中的专属订单信息为空");
            redisUtil.set(EXCLUSIVE_OVERRIDE,String.valueOf(exclusivelCount));
        }else{
            //取车辆id
            List<Integer> exclusivelCarIds = new ArrayList<>(orderExclusivelDtoList.size());
            orderExclusivelDtoList.forEach(orderExclusivelDto -> {
                if (orderExclusivelDto.getCarId() != null && orderExclusivelDto.getCarId() > 0) {
                    exclusivelCarIds.add(orderExclusivelDto.getCarId());
                }
            });

            // 根据车辆ids查询车辆信息
            Map<Integer, CarDto> exclusivelCarMap = carService.getCarByIds(exclusivelCarIds);
            if (exclusivelCarMap == null || exclusivelCarMap.isEmpty()) {
                log.error("专属根据车辆ids查询车辆信息异常：车辆信息(ids:" + exclusivelCarMap + ")查询异常");
                return false;
            }

            // 车架号vins
            List<String> exclusivelVins = exclusivelCarMap.entrySet().stream().map(e -> e.getValue().getVin()).collect(Collectors.toList());
            // 根据车架号查询车辆行驶里程信息
            Map<String, Integer> exclusivelCurrentMileageMap = iovCarService.getCurrentMileage(exclusivelVins);
            if (exclusivelCurrentMileageMap == null || exclusivelCurrentMileageMap.isEmpty()) {
                log.error("专属根据车辆ids查询车辆里程信息异常：车辆信息(ids:" + exclusivelVins + ")查询异常");
                return false;
            }

            for (OrderExclusivelDto orderExclusivelDto:orderExclusivelDtoList) {
                //当前车辆的行驶里程
                if(null != exclusivelCurrentMileageMap.get(exclusivelCarMap.get(orderExclusivelDto.getCarId()).getVin())){
                    // 当前车辆的行驶里程 > 当前车辆的预警里程
                    if(exclusivelCurrentMileageMap.get(exclusivelCarMap.get(orderExclusivelDto.getCarId()).getVin()) > orderExclusivelDto.getWarningMileage() ){
                        exclusivelCount++;
                    }
                }
            }

            redisUtil.set(EXCLUSIVE_OVERRIDE,String.valueOf(exclusivelCount));

        }

        return true;
    }





    /**
     * 昨天专属订阅数量
     * @return
     */
    @Override
    public Boolean yesterdayOrderCount(Integer day) throws Exception {

        try {


            //订阅
            Integer subscribeCount = orderSubscribeService.getSubscribeYesterdayCount(day);
            basicdataStatisticsOrderService.createStatisticsOrder(getStatisticsOrderCreateDto(day,StatisticsOrderTypeEnum.SUBSCRIBE,subscribeCount));

            //专属
            Integer exclusivelCount = orderExclusivelService.getExclusivelYesterdayCount(day);
            basicdataStatisticsOrderService.createStatisticsOrder(getStatisticsOrderCreateDto(day,StatisticsOrderTypeEnum.EXCLUSIVE,exclusivelCount));



        } catch (Exception e) {
            log.error("查询昨天专属订阅数量异常：" , e);
            throw new Exception("查询昨天专属订阅数量异常");
        }
        return true;
    }

    private StatisticsOrderCreateDto getStatisticsOrderCreateDto(Integer day,StatisticsOrderTypeEnum orderTypeEnum, Integer count) {
        StatisticsOrderCreateDto statisticsOrderCreateDto = new StatisticsOrderCreateDto();
        statisticsOrderCreateDto.setStatisticsDate(LocalDate.now().minusDays(day));
        statisticsOrderCreateDto.setOrderCount(count);
        statisticsOrderCreateDto.setOrderType(orderTypeEnum.getValue());
        return statisticsOrderCreateDto;
    }







}
